package StudyCode.summary.myfile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class FileExtract {
	public static void main(String[] argv) throws Exception {
		File archive = new File("E:\\迅雷下载\\test1.txt");
		File targetDir = new File("E:\\迅雷下载\\test1.txt");
		System.out.println("解压成功？" + extract(archive, targetDir));
	}

	private static final String[] SUPPORTED_FILES = new String[]{".zip", ".jar", ".war"};

	private static boolean extract(File archive, File targetDir)
			throws IOException {
		return extract(archive.toURI().toURL(), targetDir);
	}

	private static boolean extract(URL archive, File targetDir) throws IOException {
		String archiveStr = archive.toString();
		String jarEntry = null;
		int idx = archiveStr.indexOf("!/");
		if (idx != -1) {
			if (!archiveStr.startsWith("jar:")
					&& archiveStr.length() == idx + 2)
				return false;
			archive = new URL(archiveStr.substring(4, idx));
			jarEntry = archiveStr.substring(idx + 2);
		} else if (!isSupported(archiveStr))
			return false;

		JarInputStream jis = new JarInputStream(archive.openConnection()
				.getInputStream());
		if (!targetDir.exists())
			targetDir.mkdirs();
		JarEntry entry = null;
		while ((entry = jis.getNextJarEntry()) != null) {
			String entryName = entry.getName();
			File entryFile = new File(targetDir, entryName);
			if (!entry.isDirectory()) {
				if (jarEntry == null || entryName.startsWith(jarEntry)) {
					if (!entryFile.exists()
							|| entryFile.lastModified() != entry.getTime())
						extractEntry(entryFile, entry);
				}
			}
		}
		try {
			jis.close();
		} catch (Exception ignored) {
		}
		return true;
	}

	private static boolean isSupported(String resource) {
		int idx = resource.lastIndexOf('.');
		if (resource.length() == idx + 4) {
			for (String SUPPORTED_FILE : SUPPORTED_FILES) {
				if (resource.endsWith(SUPPORTED_FILE))
					return true;
			}
		}
		return false;
	}

	private static void extractEntry(File entryFile, JarEntry entry) {
		File parent = new File(entryFile.getParent());
		if (!parent.exists()) {
			parent.mkdirs();
		}
		entryFile.setLastModified(entry.getTime());

	}
}
